<template>
  <div class="container">
    <Breadcrumb />
    <a-card class="data-card">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
          >
            <a-row :gutter="20">
              <a-col :span="5">
                <a-form-item field="teacherNo" label="用户名">
                  <a-input
                    v-model="formModel.teacherNo"
                    placeholder="请输入用户名"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="5">
                <a-form-item field="teacherName" label="姓名">
                  <a-input
                    v-model="formModel.teacherName"
                    placeholder="请输入姓名"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="5">
                <a-form-item field="sex" label="性别">
                  <a-select
                    v-model="formModel.sex"
                    :options="sexs"
                    placeholder="请选择性别"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="5">
                <a-form-item field="deptId" label="部门">
                  <a-cascader
                    v-model="formModel.deptId"
                    check-strictly
                    :options="depts"
                    placeholder="请选择所在部门"
                    :field-names="props"
                    :show-all-levels="false"
                    allow-clear
                  ></a-cascader>
                </a-form-item>
              </a-col>
              <!-- <a-col :span="5">
                <a-form-item field="isLocking" label="锁定状态">
                  <a-select
                    v-model="formModel.isLocking"
                    :options="isLockings"
                    placeholder="请选择锁定状态"
                    allow-clear
                  />
                </a-form-item>
              </a-col> -->
              <a-col :span="5">
                <a-space :size="18">
                  <a-button type="primary" @click="onPageChange(1)">
                    <template #icon>
                      <icon-search />
                    </template>
                    搜索
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    重置
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button @click="openAdd" type="primary">
              <template #icon>
                <icon-plus />
              </template>
              新增
            </a-button>
            <a-button @click="openUpload"> 批量导入 </a-button>
          </a-space>
        </a-col>
        <a-col
          :span="12"
          style="display: flex; align-items: center; justify-content: end"
        >
          <a-space>
            <a-button @click="downloadUser">
              <template #icon>
                <icon-download />
              </template>
              批量导出
            </a-button>
            <a-button type="primary" @click="pldel" status="danger">
              批量删除
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-table
        ref="userList"
        row-key="teacherId"
        v-model:selectedKeys="userIds"
        :loading="loading"
        page-position="bottom"
        :pagination="pagination"
        :row-selection="rowSelection"
        :columns="columns"
        :data="renderData"
        :bordered="false"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #sex="{ record }">
          <template v-for="(item, index) in sexs">
            <span v-if="record.sex == item.value">{{ item.label }}</span>
          </template>
        </template>
        <!-- <template #isLocking="{ record }">
          <template v-for="(item, index) in isLockings">
            <span v-if="record.isLocking == item.value">{{ item.label }}</span>
          </template>
        </template> -->
        <template #option="{ record }">
          <a-space :size="18">
            <a-button type="outline" @click="openRePass(record)">
              重置密码
            </a-button>

            <a-button @click="openEdit(record)" type="primary"> 编辑 </a-button>
            <a-button
              status="danger"
              @click="openDelete(record)"
              v-if="record.teacherNo != 'admin'"
            >
              删除
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>
    <a-modal
      v-model:visible="addShow"
      @cancel="handleCancel"
      :on-before-ok="handleCheck"
      :mask-closable="false"
      unmountOnClose
      width="900px"
    >
      <template #title> 用户 </template>
      <a-form ref="addModel" :rules="rules" :model="addForm">
        <a-row style="margin-bottom: 16px">
          <a-col :span="12">
            <a-form-item field="teacherNo" label="用户名">
              <a-input
                v-model="addForm.teacherNo"
                size="large"
                placeholder="请输入用户名"
                :disabled="addForm.teacherId ? true : false"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :field="addForm.teacherId ? 'sss' : 'password'"
              label="密码"
            >
              <a-input-password
                v-model="addForm.password"
                size="large"
                placeholder="请输入密码"
              />
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item field="teacherName" label="姓名">
              <a-input
                v-model="addForm.teacherName"
                size="large"
                placeholder="请输入姓名"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="sex" label="性别">
              <a-select
                v-model="addForm.sex"
                :options="sexs"
                placeholder="请选择性别"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="mobile" label="手机号">
              <a-input
                v-model="addForm.mobile"
                size="large"
                placeholder="请输入手机号"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="deptId" label="部门">
              <a-cascader
                v-model="addForm.deptId"
                check-strictly
                :options="depts"
                placeholder="请选择所在部门"
                :field-names="props"
                :show-all-levels="false"
              ></a-cascader>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item field="roleId" label="角色">
              <a-select
                v-model="addForm.roleId"
                :options="roles"
                :field-names="rolesFields"
                placeholder="请选择性别"
              />
            </a-form-item>
          </a-col>

          <!-- <a-col :span="12">
            <a-form-item field="majorId" label="专业">
              <a-select
                v-model="addForm.majorIdsArr"
                @change="majorChange"
                :options="majors"
                :max-tag-count="1"
                :field-names="majorsFields"
                multiple
                placeholder="请选择专业"
              />
            </a-form-item>
          </a-col> -->
          <a-col :span="12">
            <a-form-item field="majorId" label="专业">
              <a-tree-select
                v-model="addForm.majorId"
                :data="majors"
                :max-tag-count="1"
                :fieldNames="majorsFields"
                placeholder="请选择专业"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
    <a-modal
      v-model:visible="uploadShow"
      @cancel="uploadCancel"
      :on-before-ok="uploadCheck"
      :mask-closable="false"
      unmountOnClose
      width="450px"
    >
      <template #title> 导入用户 </template>
      <a-form ref="uploadModel" :rules="uploadRules" :model="uploadForm">
        <a-row style="margin-bottom: 16px">
          <a-form-item field="deptId" label="部门">
            <a-cascader
              v-model="uploadForm.deptId"
              check-strictly
              :options="depts"
              placeholder="请选择所在部门"
              :field-names="props"
              :show-all-levels="false"
            ></a-cascader>
          </a-form-item>

          <a-form-item field="roleId" label="角色">
            <a-select
              v-model="uploadForm.roleId"
              :options="roles"
              :field-names="rolesFields"
              placeholder="请选择性别"
            />
          </a-form-item>
          <a-form-item field="majorId" label="专业">
            <a-tree-select
              v-model="uploadForm.majorId"
              :data="majors"
              :field-names="majorsFields"
              placeholder="请选择专业"
            />

            <!-- <a-tree-select
                v-model="addForm.majorId"
                :data="majors"
                :max-tag-count="1"
                :fieldNames="majorsFields"
                placeholder="请选择专业"
              /> -->
          </a-form-item>
          <a-form-item field="file" label="文件">
            <a-upload
              class="upload_box"
              @change="onChange"
              accept=".xls,.xlsx"
              ref="uploadRef"
              :auto-upload="false"
              :limit="1"
            >
              <template #upload-button>
                <a-space>
                  <a-button type="primary">选择附件</a-button>
                  <a-button @click.stop="downloadTemplate">下载模板</a-button>
                </a-space>
              </template>
            </a-upload>
          </a-form-item>
        </a-row>
      </a-form>
    </a-modal>
    <a-modal
      v-model:visible="lockShow"
      @cancel="lockCancel"
      :on-before-ok="lockCheck"
      :mask-closable="false"
      unmountOnClose
      width="450px"
    >
      <template #title> 解锁用户 </template>
      <a-form ref="lockModel" :rules="lockRules" :model="lockForm"> </a-form>
    </a-modal>
  </div>
</template>
<script lang="ts">
  export default {
    name: 'user',
  };
</script>
<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick } from 'vue';
  import useLoading from '@/hooks/loading';
  import { useSelectionStore } from '@/store';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  import { Message, Modal } from '@arco-design/web-vue';
  import {
    adminUserList,
    adminUserSave,
    adminUserUpdate,
    adminUserRemove,
    resetPassword,
    importAdminUser,
    adminUserExport,
    downloadTemplate,
    unlockUserBatch,
  } from '@/api/adminUser.ts';
  import { deptTree } from '@/api/dept.ts';
  import { organizationTree } from '@/api/organization.ts';
  import { roleList } from '@/api/role.ts';
  import { majorTree } from '@/api/major.ts';

  const { loading, setLoading } = useLoading(true);

  const generateDataModel = () => {
    return {
      teacherId: '',
      teacherNo: '',
      teacherName: '',
      sex: '',
      mobile: '',
      deptId: '',
      roleId: '',
      organizationList: [],
      majorId: '',
      majorIdsArr: [],
    };
  };

  const rules = {
    password: [
      {
        required: true,
        message: '请输入用户名',
      },
      {
        minLength: 4,
        message: '最少输入四位',
      },
    ],
    teacherNo: [
      {
        required: true,
        message: '请输入用户名',
      },
      {
        minLength: 4,
        message: '最少输入四位',
      },
    ],
    teacherName: [
      {
        required: true,
        message: '请输入姓名',
      },
    ],
    sex: [
      {
        required: true,
        message: '请选择性别',
      },
    ],
    deptId: [
      {
        required: true,
        message: '请选择部门',
      },
    ],
    roleId: [
      {
        required: true,
        message: '请选择角色',
      },
    ],
    // organizationList: [
    //   {
    //     required: true,
    //     message: '请选择班级',
    //   },
    // ],
    mobile: [
      {
        required: true,
        message: '请输入手机号',
      },
      {
        minLength: 11,
        message: '请输入11位的手机号',
      },
    ],
  };
  const addForm = ref(generateDataModel());
  const addShow = ref(false);
  const addModel = ref();

  const openAdd = () => {
    addForm.value = generateDataModel();
    addShow.value = true;
  };

  //   const majorChange = (majorIdsArr) => {
  //     if (majorIdsArr && majorIdsArr.length) {
  //       addForm.value.majorId = majorIdsArr.join(',');
  //     } else {
  //       addForm.value.majorId = '';
  //     }
  //   };

  const handleCheck = (done) => {
    if (loading.value) {
      done(false);
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    addModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          if (addForm.value.teacherId) {
            adminUserUpdate(addForm.value).then((res) => {
              if (res.code == '200') {
                Message.success({
                  content: res.message,
                });
                done(true);
                reset();
              } else {
                done(false);
              }
            });
          } else {
            adminUserSave(addForm.value).then((res) => {
              if (res.code == '200') {
                Message.success({
                  content: res.message,
                });
                done(true);
                reset();
              } else {
                done(false);
              }
            });
          }
        } else {
          done(false);
        }
      }
    );
  };

  const openEdit = (item) => {
    // let majorIdsArr = [];
    if (item.majorId) {
      //   majorIdsArr = item.majorId.split(',');
      //   majorIdsArr = majorIdsArr.map((item) => {
      //     return +item;
      //   });
    }
    addForm.value = Object.assign({}, item, {
      //   majorIdsArr: majorIdsArr,
    });
    console.log('编辑', addForm.value);

    addShow.value = true;
  };

  const handleCancel = () => {
    addShow.value = false;
  };
  const openDelete = (item) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除吗？',
      onOk() {
        adminUserRemove({
          teacherId: item.teacherId,
        }).then((res) => {
          if (res.code == '200') {
            Message.success({
              content: res.message,
            });
            fetchData();
          }
        });
      },
    });
  };
  const pldel = () => {
    if (userIds.value.length == 0) {
      Modal.confirm({
        title: '提示',
        content: '请先选中要删除的用户？',
      });
    } else {
      Modal.confirm({
        title: '提示',
        content: '确定批量删除吗',
        onOk() {
          Promise.all(
            userIds.value.map((teacherId) => {
              return adminUserRemove({
                teacherId: teacherId,
              }).then((res) => {
                if (res.code == '200') {
                  Message.success({
                    content: '删除成功',
                  });
                  fetchData();
                }
              });
            })
          )
            .then((results) => {
              // 检查所有结果是否都为 true，表示删除成功
              if (results.every((result) => result === true)) {
                // 如果所有删除成功，显示成功提示
                Message.success({
                  content: '删除成功',
                });

                // 然后重新获取数据
                fetchData();
              }
            })
            .catch((err) => {
              fetchData();
              console.error('失败:', err);
            });
        },
      });
    }
  };
  const openRePass = (item) => {
    Modal.confirm({
      title: '提示',
      content: '确认重置此用户密码吗？',
      onOk() {
        resetPassword({
          teacherId: item.teacherId,
        }).then((res) => {
          if (res.code == '200') {
            Message.success({
              content: res.message,
            });
          }
        });
      },
    });
  };

  const lockForm = ref(generateLockModel());

  const lockShow = ref(false);
  const lockModel = ref();
  const userIds = ref([]);

  const lockCheck = (done) => {
    if (loading.value) {
      done(false);
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    lockModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          unlockUserBatch(lockForm.value).then((res) => {
            if (res.code == '200') {
              done(true);
              reset();
              Message.success({
                content: res.message,
              });
            } else {
              done(false);
            }
          });
        } else {
          done(false);
        }
      }
    );
  };
  const lockCancel = () => {
    lockShow.value = false;
  };

  const generateUploadModel = () => {
    return {
      file: null,
      deptId: '',
      roleId: '',

      majorId: '',
      majorIdsArr: [],
    };
  };

  const uploadRules = {
    deptId: [
      {
        required: true,
        message: '请选择部门',
      },
    ],
    roleId: [
      {
        required: true,
        message: '请选择角色',
      },
    ],

    file: [
      {
        required: true,
        message: '请选择附件',
      },
    ],
  };
  const uploadForm = ref(generateUploadModel());
  const uploadShow = ref(false);
  const uploadModel = ref();
  const openUpload = () => {
    uploadForm.value = generateDataModel();
    uploadShow.value = true;
  };

  const majorUpChange = (majorIdsArr) => {
    if (majorIdsArr && majorIdsArr.length) {
      uploadForm.value.majorId = majorIdsArr.join(',');
    } else {
      uploadForm.value.majorId = '';
    }
  };
  const onChange = (fileList) => {
    if (fileList && fileList.length > 0) {
      uploadForm.value.file = fileList[0].file;
    } else {
      uploadForm.value.file = null;
    }
  };

  const uploadCheck = (done) => {
    if (loading.value) {
      done(false);
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    uploadModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          let formData = new FormData();
          formData.append('deptId', uploadForm.value.deptId);
          formData.append('roleId', uploadForm.value.roleId);
          formData.append('majorId', uploadForm.value.majorId);
          formData.append('file', uploadForm.value.file);
          importAdminUser(formData).then((res) => {
            if (res.code == '200') {
              Message.success({
                content: res.message,
              });
              reset();
              done(true);
            } else {
              done(false);
            }
          });
        } else {
          done(false);
        }
      }
    );
  };
  const uploadCancel = () => {
    uploadShow.value = false;
  };

  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const columns = computed<TableColumnData[]>(() => [
    {
      title: '用户名',
      dataIndex: 'teacherName',
    },
    {
      title: '姓名',
      dataIndex: 'teacherName',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      slotName: 'sex',
      align: 'center',
    },
    {
      title: '部门',
      dataIndex: 'deptName',
    },
    {
      title: '角色',
      dataIndex: 'roleName',
      align: 'center',
    },

    {
      title: '操作',
      dataIndex: 'option',
      slotName: 'option',
      align: 'center',
    },
  ]);

  const sexs = useSelectionStore().sexs;

  const generateFormModel = () => {
    return {
      teacherNo: '',
      teacherName: '',
      deptId: '',
      sex: '',
    };
  };

  const formModel = ref(generateFormModel());
  const renderData = ref([]);
  const userList = ref();

  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const pagination = reactive({
    ...basePagination,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });

  const fetchData = async () => {
    setLoading(true);
    try {
      const data = {
        pageNum: pagination.current,
        ...pagination,
        ...formModel.value,
      };
      adminUserList(data).then((res) => {
        let list = res.data.list || [];

        renderData.value = list;
        pagination.total = res.data.total;
        pagination.current = res.data.current;

        userList.value.selectAll(false);
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
  };
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    fetchData();
  };

  const reset = () => {
    formModel.value = generateFormModel();
    fetchData();
  };
  fetchData();

  const downloadUser = () => {
    adminUserExport(formModel.value).then((res) => {});
  };

  const depts = ref([]);
  const props = {
    value: 'id',
    label: 'name',
  };
  const getDepts = () => {
    deptTree().then((res) => {
      depts.value = res.data || [];
    });
  };
  getDepts();

  const roles = ref([]);
  const rolesFields = {
    value: 'roleId',
    label: 'roleName',
  };
  const getRoles = () => {
    roleList().then((res) => {
      roles.value = res.data || [];
    });
  };
  getRoles();

  const organizations = ref([]);
  const organizationsFields = {
    value: 'id',
    label: 'name',
  };
  const getOrganizations = () => {
    organizationTree().then((res) => {
      organizations.value = res.data || [];
    });
  };
  getOrganizations();

  const majors = ref([]);
  const majorsFields = {
    key: 'id',
    title: 'name',
    children: 'children',
    // value: 'id',
    // label: 'name',
  };
  const getMajors = () => {
    majorTree().then((res) => {
      majors.value = res.data || [];
    });
  };
  getMajors();
</script>
